<template>
  <div>
    <!-- 登录 -->
    <div class="menu-login">
      <div v-if="userInfo">
        <el-dropdown trigger="click">
         <span class="el-dropdown-link nickname-span">
            {{userInfo.nickname}}
          </span>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="clickExitLogin">
                <span>退出登录</span>
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
      <div v-else>
        <el-button type="warning" @click="loginDrawer=true">登录</el-button>
      </div>
    </div>

    <!-- 固定位置的按钮 -->
    <div class="menu-button">
      <el-button type="danger" :icon="House" circle @click="goPageByMenuLinkUrl('/')"/>
      <el-button type="warning" :icon="Edit" circle @click="goPageByMenuLinkUrl('/articleAdd')"/>
      <el-button type="primary" :icon="Search" circle @click="searchDrawer=true" v-if="false"/>
      <el-button type="success" :icon="Expand" circle @click="menuDrawer=true"/>
    </div>

    <!-- 搜索抽屉 -->
    <el-drawer
        v-model="searchDrawer"
        size="100%"
        :show-close="false"
        :lock-scroll="false">
      <template #header="{ close }">
        <h4 class="drawerHeaderTitle">博客搜索!</h4>
        <el-button type="danger" @click="close">
          <el-icon class="el-icon--left"><CircleCloseFilled /></el-icon>
          Close
        </el-button>
      </template>
      <div class="search-box">
        <div class="wrapper">
          <div class="input-data">
            <input v-model="searchKeyword" required type="text" @keyup.enter.native="goSearch()">
            <div class="underline"></div>
            <label>搜索内容</label>
          </div>
        </div>
      </div>
    </el-drawer>

    <!-- 导航抽屉 -->
    <el-drawer
        v-model="menuDrawer"
        size="100%"
        :show-close="false"
        :lock-scroll="false">
      <template #header="{ close }">
        <h4 class="drawerHeaderTitle">博客导航!</h4>
        <el-button type="danger" @click="close">
          <el-icon class="el-icon--left"><CircleCloseFilled /></el-icon>
          Close
        </el-button>
      </template>

      <!-- 导航列表 -->
      <div class="menu-box">
        <div v-for="(item,index) in menuList"
             :key="'menu_nav_' + index"
             class="menu-text"
             @click="goPageByMenuLinkUrl(item.linkUrl)">
          {{item.menuName}}
        </div>
      </div>
    </el-drawer>

    <!-- 登录抽屉 -->
    <el-drawer
        v-model="loginDrawer"
        direction="ltr"
        size="40%"
        :show-close="false"
        :lock-scroll="false">
      <template #header="{ close }">
        <h4 class="drawerHeaderTitle">博客登录!</h4>
        <el-button type="danger" @click="close">
          <el-icon class="el-icon--left"><CircleCloseFilled /></el-icon>
          Close
        </el-button>
      </template>
      <div class="login-register-box">
        <div class="container">
          <div class="form-box" :class="isLogin?'translateX0':'translateX80'">
            <!-- 注册 -->
            <div class="register-box" :class="isLogin?'hidden':''">
              <h1>register</h1>
              <input type="text" placeholder="昵称" v-model="registerForm.nickname"/>
              <input type="email" placeholder="邮箱" v-model="registerForm.email"/>
              <div class="captcha-code">
                <input type="number" placeholder="验证码" v-model="registerForm.captchaCode"/>
                <el-button @click="clickSendEmail('1')" :loading="sendEmailDownTime>0">{{sendEmailDownTime<=0?'发送邮件':sendEmailDownTime+'s'}}</el-button>
              </div>
              <button @click="clickRegister">注册</button>
            </div>
            <!-- 登录 -->
            <div class="login-box" :class="isLogin?'':'hidden'">
              <h1>login</h1>
              <input type="text" placeholder="邮箱" v-model="loginForm.email"/>
              <div class="captcha-code">
                <input type="number" placeholder="验证码" v-model="loginForm.captchaCode"/>
                <el-button @click="clickSendEmail('2')" :loading="sendEmailDownTime>0">{{sendEmailDownTime<=0?'发送邮件':sendEmailDownTime+'s'}}</el-button>
              </div>
              <button @click="clickLogin">登录</button>
            </div>
          </div>
          <div class="con-box left">
            <h2>欢迎来到<span>xu的博客</span></h2>
            <p>快来注册你的<span>个人账号</span>吧</p>
            <img src="../../assets/images/cat/1.png" alt="">
            <p>已有账号</p>
            <button id="login" @click="isGoLogin(true)">去登录</button>
          </div>
          <div class="con-box right">
            <h2>欢迎来到<span>xu的博客</span></h2>
            <p>快来登录你的<span>个人账号</span>吧</p>
            <img src="../../assets/images/cat/2.png" alt="">
            <p>没有账号？</p>
            <button @click="isGoLogin(false)">去注册</button>
          </div>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script setup>
import {
  House,
  Search,
  Expand,
  Edit,
  CircleCloseFilled
} from '@element-plus/icons-vue';
import { nextTick,ref,inject} from "vue";
import { ElMessage,ElInput } from 'element-plus';

import {sendEmail,registerUser,loginUser} from "@/api/personalUser";
import { setToken,getCookieUser,removeToken } from "@/utils/auth";

import {useRouter} from "vue-router";
import {useStore} from "vuex";
const store = useStore();

// 菜单盒子
let menuDrawer = ref(false);
// 搜索盒子
let searchDrawer = ref(false);
// 登录盒子
let loginDrawer = ref(false);
// 搜索关键字
let searchKeyword = ref(undefined);
// 用户信息
let userInfo = ref(null);
// 刷新页面
const reload = inject('reload');

// 每次进入刷新一下
reUserInfo();

// 注册表单
let registerForm = ref({
  nickname:undefined,
  email:undefined,
  captchaCode:undefined,
});

// 登录表单
let loginForm = ref({
  email:undefined,
  captchaCode:undefined,
})

let isLogin = ref(true);

const router = useRouter();

// 发送邮件倒计时
let sendEmailDownTime = ref(0);

// 菜单列表
let menuList = [
  {
    menuName:'前端',
    linkUrl:'/cateArticleList?type=1&menuName=前端',
  },
  {
    menuName:'后端',
    linkUrl:'/cateArticleList?type=2&menuName=后端',
  },
  {
    menuName:'数据库',
    linkUrl:'/cateArticleList?type=3&menuName=数据库',
  },
  {
    menuName:'其他',
    linkUrl:'/cateArticleList?type=4&menuName=其他',
  },
  {
    menuName:'弹幕测试',
    linkUrl:'/barrage',
  },
  {
    menuName:'友链',
    linkUrl:'/friend',
  },
  {
    menuName:'关于本站',
    linkUrl:'/about',
  }
];


/** 去搜索页面 */
function goSearch(){
  let searchKeywordValue = searchKeyword.value;
  if(searchKeywordValue && searchKeywordValue.trim().length>0){
    console.log('有效值')
  }else {
    console.log('无效值')
  }
}

/**
 * 刷新个人信息
 */
function reUserInfo(){
  // 设置值
  userInfo.value = getCookieUser();
}

/**
 * 点击退出登录
 */
function clickExitLogin(){
  removeToken();
  reUserInfo();
}

/** 点击登录 */
async function clickLogin(){
  if(validLoginForm()){
    let res = await loginUser(loginForm.value);
    // 设置token的值
    if (res) {
      await setToken(res.data);
      // 关闭窗口
      loginDrawer.value = false;
      // 刷新
      await reload();
    }
  }
}

/** 点击注册 */
async function clickRegister(){
  if(validRegisterForm()){
    let res = await registerUser(registerForm.value);
    // 设置token的值
    if (res.code === 200) {
      await setToken(res.data);
      // 关闭窗口
      loginDrawer.value = false;
      await store.dispatch('updateStationInfo');
      // 刷新
      await reload();
    }
  }
}

/** 是否去登录，不是则去注册 */
function isGoLogin(flag){
  isLogin.value = flag
}

// 验证登录
function validLoginForm(){
  let num = 0;
  if(loginForm.value.email){
    num++;
  }else {
    ElMessage.error('请先输入邮箱');
    return num;
  }
  if(loginForm.value.captchaCode){
    num++;
  }else {
    ElMessage.error('请先输入验证码');
    return num;
  }
  // 全验证
  return num===2;
}

// 验证注册
function validRegisterForm(){
  let num = 0;
  if(registerForm.value.nickname){
    num++;

  }else {
    ElMessage.error('请先输入昵称');
    return num;
  }
  if(registerForm.value.email){
    num++;
  }else {
    ElMessage.error('请先输入邮箱');
    return num;
  }
  if(registerForm.value.captchaCode){
    num++;
  }else {
    ElMessage.error('请先输入验证码');
    return num;
  }
  // 全验证
  return num===3;
}

/** 发送邮件 */
function clickSendEmail(type){
  let flag = false;
  let email = '';
  if(registerForm.value.email && type === '1'){
    flag = true;
    email = registerForm.value.email;
  }else if(loginForm.value.email && type === '2'){
    flag = true;
    email = loginForm.value.email;
  }else {
    ElMessage.error('请先输入邮箱');
  }
  // 如果有值
  if(flag){
    let obj = {
      email:email,
      type:type,
    }
    sendEmail(obj).then(res=>{
      console.log(res);
    });
    sendEmailDownTime.value = 60;
    // 倒计时
    let sendButtonTimer = setInterval(()=>{
      sendEmailDownTime.value --;
      if(sendEmailDownTime.value===0){
        clearInterval(sendButtonTimer);
      }

    },1000);
  }
}

/** 根据导航链接去相应的页面 */
async function goPageByMenuLinkUrl(linkUrl){
  await router.push(linkUrl);
  await reload();
}
</script>

<style scoped>
@import "./header.css";

/** 抽屉设置 */
:deep(.el-drawer){
  background-image: linear-gradient(to top, lightgrey 0%, lightgrey 1%, #e0e0e0 26%, #efefef 48%, #d9d9d9 75%, #bcbcbc 100%);
  opacity: 0.9;
}
</style>
